import json
import codecs
from docx import Document

color_set = set()
font_set = set()
size_set = set()
bold_set = set()


def read_doc(fname):
    # Document 类，不仅可以新建word文档，也可以打开一个本地文档
    doc = Document(fname)  # 想获取的文档文件名，这里是相对路径。
    # sections = doc.sections  # 获取文档章节信息
    # print(len(sections))

    paragraphs = []
    # print(len(paragraphs))
    volume_title = None
    chapter_title = None
    for p in doc.paragraphs:
        texts = process_paragraph(p)
        paragraph = Paragraph(texts)
        if paragraph.volume_title is not None:
            volume_title = paragraph.volume_title
        if paragraph.chapter_title is not None:
            chapter_title = paragraph.chapter_title
        if len(paragraph.pairs) > 0:
            paragraphs.append({"volume_title": volume_title, "chapter_title": chapter_title, "pairs": paragraph.pairs})
    return paragraphs


class Paragraph:
    def __init__(self, texts):
        self.pairs = []
        self.volume_title = None
        self.chapter_title = None
        text = ""
        comment = ""
        for i in range(len(texts)):
            if texts[i].role == "text":
                if i > 0 and texts[i - 1].role == "text":
                    text += texts[i].text
                else:
                    if len(comment) > 0 and len(text) > 0:
                        self.pairs.append((text, comment))
                    text = texts[i].text
                    comment = ""
            elif texts[i].role == "comment":
                if i > 0 and texts[i - 1].role == "comment":
                    comment += texts[i].text
                else:
                    comment = texts[i].text
            elif texts[i].role == "volume_title":
                self.volume_title = texts[i].text
            elif texts[i].role == "chapter_title":
                self.chapter_title = texts[i].text


class Text:
    def __init__(self, t, color, size):
        self.text = t
        self.color = color
        self.size = size
        self.role = None
        self.__set_role()

    def __set_role(self):
        if self.size == "1143000" and self.color == "0000FF":
            self.role = "volume_title"
        elif self.size == "1270000" and self.color == "FF0000":
            self.role = "book_title"
        elif self.size == "457200" and self.color == "0000FF":
            self.role = "chapter_title"
        elif self.size == "203200" and self.color == "FF0000":
            self.role = "comment"
        elif (self.size == "254000" or self.size == "203200") and self.color == "666666":
            self.role = "side_comment"
        elif self.size == "254000" and self.color == "000000":
            self.role = "text"
        else:
            print(self.size, self.color, self.text)
            raise Exception("wrong size and color")


"""
    大学章句（蓝色标题）：  1143000 0000FF
    红色注释：   203200 FF0000
    灰色注释：   254000 666666
    黑色正文：   254000 000000
"""


def process_paragraph(p):
    # paragraph对象里还有更小的run对象，run对象才包含了段落对象的文字信息。
    texts = []
    for r in p.runs:
        font = r.font.name  # 字体均为宋体
        bold = r.font.bold  # 全部为加黑

        size = str(r.font.size)
        color = str(r.font.color.rgb)
        t = Text(r.text, color, size)
        texts.append(t)
    return texts


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    paragraphs = read_doc('四书章句集注.docx')
    json.dump(paragraphs, codecs.open("sishu_comment_pair.json", "w", encoding="utf8"), ensure_ascii=False, indent=4)
